package tool;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.util.*;

public class SortedJsonBuilder {

    /**
     * 将 JSON 字段排序：
     * 1. 基础类型字段（String, Number, Boolean）放前面，按字段名字母排序
     * 2. 复杂类型字段（Object, Array）放后面，按字段名字母排序
     */
    public static JSONObject sortJsonFieldsAlphabetically(JSONObject original) {
        // 使用 LinkedHashMap 保证顺序
        Map<String, Object> sortedMap = new LinkedHashMap<>();

        // 分类：基础类型 vs 复杂类型
        List<Map.Entry<String, Object>> primitives = new ArrayList<>();
        List<Map.Entry<String, Object>> complexes = new ArrayList<>();

        for (Map.Entry<String, Object> entry : original.entrySet()) {
            Object value = entry.getValue();
            if (isPrimitive(value)) {
                primitives.add(entry);
            } else {
                complexes.add(entry);
            }
        }

        // 按字段名排序（忽略大小写 + 支持中文）
        Comparator<Map.Entry<String, Object>> comparator = Comparator.comparing(
                Map.Entry::getKey,
                String.CASE_INSENSITIVE_ORDER
        );

        primitives.sort(comparator);
        complexes.sort(comparator);

        // 先放基础类型
        for (Map.Entry<String, Object> entry : primitives) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }
        // 再放复杂类型
        for (Map.Entry<String, Object> entry : complexes) {
            sortedMap.put(entry.getKey(), entry.getValue());
        }

        return new JSONObject(sortedMap);
    }

    /**
     * 判断是否为基础类型（String, Number, Boolean）
     */
    private static boolean isPrimitive(Object value) {
        return value instanceof String ||
                value instanceof Number ||
                value instanceof Boolean;
    }

    // ========================
    // 使用示例
    // ========================
    public static void main(String[] args) {
        String jsonStr = "{\n" +
                "            \"injectScript\": null,\n" +
                "            \"serviceType\": 1001,\n" +
                "            \"subnetInstanceId\": \"4801931251206733925\",\n" +
                "            \"ecsLoginName\": \"root\",\n" +
                "            \"azName\": \"az01-cell01-pri-idc-sichuan-scdx\",\n" +
                "            \"num\": null,\n" +
                "            \"ipv6BandWidth\": null,\n" +
                "            \"networkName\": \"network_vpc03_subnet\",\n" +
                "            \"flavorInfo\": \"[{\\\"isShow\\\":\\\"1\\\",\\\"measurementUnit\\\":\\\"\\\",\\\"prtyCode\\\":\\\"cpuFrequency\\\",\\\"prtyName\\\":\\\"处理器主频\\\",\\\"prtyType\\\":\\\"0\\\",\\\"prtyValue\\\":\\\"2.2 GHz\\\"},{\\\"isShow\\\":\\\"1\\\",\\\"measurementUnit\\\":\\\"\\\",\\\"prtyCode\\\":\\\"cpuModel\\\",\\\"prtyName\\\":\\\"处理器型号\\\",\\\"prtyType\\\":\\\"0\\\",\\\"prtyValue\\\":\\\"Intel Gold 6248R\\\"},{\\\"isShow\\\":\\\"1\\\",\\\"measurementUnit\\\":\\\"vCPU\\\",\\\"prtyCode\\\":\\\"cpuNum\\\",\\\"prtyName\\\":\\\"CPU数量\\\",\\\"prtyType\\\":\\\"0\\\",\\\"prtyValue\\\":\\\"1\\\"},{\\\"isShow\\\":\\\"1\\\",\\\"measurementUnit\\\":\\\"\\\",\\\"prtyCode\\\":\\\"cpuRuiFrequency\\\",\\\"prtyName\\\":\\\"处理器睿频\\\",\\\"prtyType\\\":\\\"0\\\",\\\"prtyValue\\\":\\\"3.4 GHz\\\"},{\\\"isShow\\\":\\\"1\\\",\\\"measurementUnit\\\":\\\"\\\",\\\"prtyCode\\\":\\\"instanceFamily\\\",\\\"prtyName\\\":\\\"实例规格族\\\",\\\"prtyType\\\":\\\"0\\\",\\\"prtyValue\\\":\\\"S5\\\"},{\\\"isShow\\\":\\\"1\\\",\\\"measurementUnit\\\":\\\"\\\",\\\"prtyCode\\\":\\\"intranetBandwidth\\\",\\\"prtyName\\\":\\\"内网带宽\\\",\\\"prtyType\\\":\\\"0\\\",\\\"prtyValue\\\":\\\"1 Gbps\\\"},{\\\"isShow\\\":\\\"1\\\",\\\"measurementUnit\\\":\\\"\\\",\\\"prtyCode\\\":\\\"intranetReceivePack\\\",\\\"prtyName\\\":\\\"内网收发包\\\",\\\"prtyType\\\":\\\"0\\\",\\\"prtyValue\\\":\\\"24万 PPS\\\"},{\\\"isShow\\\":\\\"1\\\",\\\"measurementUnit\\\":\\\"GB\\\",\\\"prtyCode\\\":\\\"memorySize\\\",\\\"prtyName\\\":\\\"内存大小\\\",\\\"prtyType\\\":\\\"0\\\",\\\"prtyValue\\\":\\\"2\\\"},{\\\"isShow\\\":\\\"1\\\",\\\"measurementUnit\\\":\\\"GB\\\",\\\"prtyCode\\\":\\\"SystemDiskSize\\\",\\\"prtyName\\\":\\\"系统盘大小\\\",\\\"prtyType\\\":\\\"0\\\",\\\"prtyValue\\\":\\\"50\\\"}]\",\n" +
                "            \"masterTenantId\": \"4801647491307372563\",\n" +
                "            \"type\": \"ECS_Common\",\n" +
                "            \"uuid\": \"ad25381b-e5d8-4f56-88c7-d5808a1da7f2\",\n" +
                "            \"flavorType\": null,\n" +
                "            \"payType\": 0,\n" +
                "            \"children\": null,\n" +
                "            \"flavorUuid\": \"e7b6c576-8b8a-4692-8d9e-7ce8b3695ebc\",\n" +
                "            \"routerName\": \"xiaotong_vpc03\",\n" +
                "            \"cloudType\": \"private\",\n" +
                "            \"routerId\": \"4801908230182002788\",\n" +
                "            \"cloudId\": \"7942753377392459776\",\n" +
                "            \"imageInstanceId\": \"4801672006980747398\",\n" +
                "            \"azId\": \"4698667438408106416\",\n" +
                "            \"trait\": \"S5\",\n" +
                "            \"model\": null,\n" +
                "            \"networkId\": \"4801931251206733924\",\n" +
                "            \"azCode\": \"az01-cell01-pri-idc-sichuan-scdx\",\n" +
                "            \"id\": null,\n" +
                "            \"imageType\": \"common\",\n" +
                "            \"imageUuid\": \"2160fdc7-42bf-4c5c-b807-a60cdd904657\",\n" +
                "            \"ram\": null,\n" +
                "            \"flavorName\": \"s5.medium2\",\n" +
                "            \"imageName\": \"UBUNTU_18.04_S_64_50_R_ProMir_ECS_v6.3.raw\",\n" +
                "            \"orgName\": null,\n" +
                "            \"lastStatusChgTime\": null,\n" +
                "            \"serverGroupId\": null,\n" +
                "            \"cpu\": 1,\n" +
                "            \"hostId\": \"59b6ca9770502c48a7dd8c730993a8c610115fcd2425d1a332a98f4d\",\n" +
                "            \"intranetFloatIp\": \"100.127.2.6\",\n" +
                "            \"productArchitect\": \"x86\",\n" +
                "            \"inactiveTime\": null,\n" +
                "            \"optStatus\": \"\",\n" +
                "            \"sysExtUuid\": null,\n" +
                "            \"ssoAccountId\": null,\n" +
                "            \"serverUuid\": \"ad25381b-e5d8-4f56-88c7-d5808a1da7f2\",\n" +
                "            \"schemaType\": \"x86\",\n" +
                "            \"preHostName\": null,\n" +
                "            \"regionModel\": \"ManageOne\",\n" +
                "            \"projectName\": \"xiaotong默认项目\",\n" +
                "            \"projectId\": \"4801647749005434909\",\n" +
                "            \"localDiskSize\": null,\n" +
                "            \"status\": \"running\",\n" +
                "            \"hostName\": \"ecm0015.a.pri.idc.sichuan.scdx\",\n" +
                "            \"routerUuid\": \"fe401062-0fa7-4054-b1c6-0fcd69288aa7\",\n" +
                "            \"imageOsType\": \"linux\",\n" +
                "            \"memory\": 2,\n" +
                "            \"ipv6Address\": null,\n" +
                "            \"instanceName\": \"hlx_test03\",\n" +
                "            \"ipv6InstanceName\": null,\n" +
                "            \"regionName\": \"四川大学私有云\",\n" +
                "            \"flavorId\": 2949482,\n" +
                "            \"ipv4Address\": \"10.3.9.52\",\n" +
                "            \"typeName\": \"通用型\",\n" +
                "            \"description\": null,\n" +
                "            \"externalNetworkUuid\": null,\n" +
                "            \"sysUuid\": \"41e5383d-e27a-480e-a856-ba234dae9684\",\n" +
                "            \"subCidr\": \"10.3.9.0/24\",\n" +
                "            \"subnetName\": \"vpc03_subnet\",\n" +
                "            \"regionCode\": \"pri.idc.sichuan.scdx\",\n" +
                "            \"cloudCode\": \"wocloud\",\n" +
                "            \"instanceId\": \"4802011051699044358\",\n" +
                "            \"tenantName\": \"xiaotong_yun\",\n" +
                "            \"orgCode\": null,\n" +
                "            \"ipv6InstanceId\": null,\n" +
                "            \"masterTenantName\": \"xiaotong\",\n" +
                "            \"osType\": null,\n" +
                "            \"networkUuid\": \"a7569d4a-0399-4636-8366-5fdde6f07355\",\n" +
                "            \"preHostId\": null,\n" +
                "            \"policy\": null,\n" +
                "            \"serverGroupName\": null,\n" +
                "            \"loginMethod\": 1,\n" +
                "            \"regionVersion\": \"r\",\n" +
                "            \"optStatusChgTime\": null,\n" +
                "            \"publicIp\": \"\",\n" +
                "            \"osName\": \"Linux\",\n" +
                "            \"userName\": \"胡林兴\",\n" +
                "            \"azUuid\": \"az01-cell01-pri-idc-sichuan-scdx\",\n" +
                "            \"subnetUuid\": \"bf134c17-f808-4f50-8f49-84ef701a2854\",\n" +
                "            \"customType\": \"normal\",\n" +
                "            \"isBandIp\": 0,\n" +
                "            \"createTime\": \"1755589975000\",\n" +
                "            \"regionId\": \"4698667438408105986\",\n" +
                "            \"cloudName\": \"联通云(私有云)\",\n" +
                "            \"localDiskNum\": 0,\n" +
                "            \"tenantId\": \"4801647749005434911\",\n" +
                "            \"localDiskType\": null\n" +
                "        }";
        JSONObject original = JSON.parseObject(jsonStr);
        JSONObject sorted = sortJsonFieldsAlphabetically(original);

        System.out.println("✅ 按字母排序后结果：");
        System.out.println(sorted.toJSONString());
    }
}